﻿using System.Security.Claims;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Provenance.Domain;
using Provenance.Domain.User;
using Provenance.ErrorCount;
using Provenance.Infra;
using Provenance.Read.Api.Application.Command.User;
using Provenance.Read.Api.Dto.User;
using Provenance.Read.Api.Utilities;

namespace Provenance.Read.Api.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class UserController : ControllerBase
    {
        private readonly IMediator _mediator;
        /// <summary>
        /// 上下文访问器
        /// </summary>
        private readonly IHttpContextAccessor _httpContextAccessor;
        /// <summary>
        /// 短信客户端工厂
        /// </summary>
        private readonly SmsClientFactory _smsClientFactory;
        private readonly ProvenanceDbContext _dbContext;

        public UserController(IMediator mediator, IHttpContextAccessor httpContextAccessor, SmsClientFactory smsClientFactory, ProvenanceDbContext dbContext)
        {
            _mediator = mediator;
            _httpContextAccessor = httpContextAccessor;
            _smsClientFactory = smsClientFactory;
            _dbContext = dbContext;
        }

        #region 用户操作
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<ApiResult<LoginResponseDTO>> Login ([FromQuery] LoginCommand command)
        {
            return await _mediator.Send(command);
        }
        /// <summary>
        /// 获取当前用户信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]      
        public async Task<IActionResult> GetUserInfo()
        {
            // 获取当前用户的 ClaimsPrincipal
            var user = _httpContextAccessor.HttpContext.User;

            // 创建一个字典来存储用户信息
            var userInfo = new Dictionary<string, string>
            {
                 // 从 ClaimsPrincipal 中提取特定的声明
                { "Name", user.FindFirst(type: ClaimTypes.Name)?.Value },// 获取用户名
                { "Id", user.FindFirst(type: ClaimTypes.NameIdentifier)?.Value }// 获取用户 Id
            };

            return Ok(userInfo);
        }
        /// <summary>
        /// 后台给用户发送短信
        /// </summary>
        [HttpPost]
        [AllowAnonymous]
        public IActionResult SendSms(string phone)
        {
            // 生成动态验证码
            string code = GenerateRandomCode(4);

            // 发送短信
            _smsClientFactory.SendSms(phone, $"{{\"code\":\"{code}\"}}", "天天Study", "SMS_476375003");

            // 存储验证码及过期时间（一个月后过期）
            try
            {
                var smsCode = new SmsCode
                {
                    Phone = phone,
                    Code = code,
                    Expiry = DateTime.Now.AddMonths(1)
                };
                _dbContext.SmsCodes.Add(smsCode);
                _dbContext.SaveChanges();

                return Ok(new { message = "验证码已发送" });
            }
            catch (Exception ex)
            {
                // 处理异常，例如记录日志
                return StatusCode(500, new { message = "发送验证码失败", error = ex.Message });
            }
        }


        /// <summary>
        /// 验证输入短信验证码是否超时或错误
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public IActionResult VerifyCode([FromBody] VerifyCodeRequest request)
        {
            try
            {
                // 从数据库中查找验证码
                var smsCode = _dbContext.SmsCodes
                    .FirstOrDefault(sc => sc.Phone == request.Phone);

                if (smsCode != null)
                {
                    // 检查验证码是否过期和匹配
                    if (smsCode.Expiry > DateTime.Now && smsCode.Code == request.Code)
                    {
                        return Ok(new { message = "输入验证码正确" });
                    }
                    else
                    {
                        // 验证失败：验证码过期或不匹配
                        return BadRequest(new { message = "验证码无效或已过期" });
                    }
                }
                else
                {
                    // 验证失败：手机号未找到
                    return BadRequest(new { message = "手机号未找到" });
                }
            }
            catch (Exception ex)
            {
                // 处理异常，例如记录日志
                return StatusCode(500, new { message = "验证失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 生成随机验证码
        /// </summary>
        /// <param name="length"></param>
        /// <returns></returns>
        private string GenerateRandomCode(int length = 4)
        {
            Random random = new Random();
            string code = string.Empty;
            for (int i = 0; i < length; i++)
            {
                code += random.Next(0, 10).ToString(); // 生成0到9的随机数
            }
            return code;
        }
        [HttpGet]
        public async Task<ApiResult<PagingResult<IList<GetUserListResponseDTO>>>> GetUserList([FromQuery] GetUserListCommand command)
        {
            return await _mediator.Send(command);
        }
        [HttpGet]
        public async Task<ApiResult<BackUserCommandResponseDTO>> BackUser([FromQuery] BackUserCommand command)
        {
            return await _mediator.Send(command);
        }


        #endregion

        #region 角色操作
        [HttpGet]
        public async Task<ApiResult<PagingResult<IList<GetRoleListResponseDTO>>>> GetRoleList([FromQuery] GetRoleListCommand command)
        {
            return await _mediator.Send(command);
        }
        [HttpGet]
        public async Task<ApiResult<BackRoleResponseDTO>> BackRole([FromQuery] BackRoleCommand command)
        {
            return await _mediator.Send(command);
        }
        #endregion

        #region 权限操作
        /// <summary>
        /// 获取当前用户的树形权限列表
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult<IList<GetTreePermissionListResponseDTO>>> GetTreePermissionList([FromQuery] GetTreePermissionListCommand command)
        {
            return await _mediator.Send(command);
        }
        [HttpGet]
        public async Task<ApiResult<BackPermissionResponseDTO>> BackPermission([FromQuery] BackPermissionCommand command)
        {
            return await _mediator.Send(command);
        }
        [HttpGet]
        public async Task<ApiResult<PagingResult<IList<GetPermissionListResponseDTO>>>> GetPermissionList([FromQuery] GetPermissionListCommand command)
        {
            return await _mediator.Send(command);
        }
       /// <summary>
       /// 获取当前用户的API权限列表
       /// </summary>
       /// <param name="command"></param>
       /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult<IList<GetApiPermissionListResponseDTO>>> GetApiPermissionList([FromQuery] GetApiPermissionListCommand command)
        {
            return await _mediator.Send(command);
        }

        #endregion

    }
}
